package com.frxuexi.video

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.Comment
import com.frxuexi.lib_base.entity.CommentBeanItem
import com.frxuexi.lib_base.entity.VideoBeanItem
import com.frxuexi.lib_base.entity.VideoZanBean
import com.frxuexi.lib_base.mvvm.BaseFragment
import com.frxuexi.lib_base.net.Const
import com.frxuexi.lib_base.utils.LiveDataBus
import com.frxuexi.video.databinding.FragmentVideoBinding
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint


@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding,VideoViewModel>() {
    val videoAdapter by lazy { VideoAdapter() }
    val commentAdapter by lazy { CommentAdapter() }
    var videoid=0
    var position=0

    var etCount:TextView?=null
    var count=0

    var iv_zan:ImageView?=null
    var tv_zan:TextView?=null
    var tv_comment:TextView?=null


    override fun initData() {
        vm.videosData.observe(this){
            Log.i("===",it.toString())
            videoAdapter.addData(it)
            videoAdapter.notifyDataSetChanged()
            videoid=it.get(0).id!!
            vm.getZan(videoid)
            iv_zan=videoAdapter.getViewByPosition(0, R.id.iv_love) as? ImageView
            tv_zan=videoAdapter.getViewByPosition(0, R.id.tv_love) as? TextView
            etCount=videoAdapter.getViewByPosition(0, R.id.etcount) as? TextView
            tv_comment=videoAdapter.getViewByPosition(0, R.id.tv_comment) as? TextView
            vm.getComments(videoid)
        }

        vm.zanData.observe(this){
            if(it>0){
                iv_zan?.setImageResource(R.drawable.ic_xihuanred)
                tv_zan?.setText("${1}")
            }else{
                iv_zan?.setImageResource(R.drawable.ic_action_nolove)
                tv_zan?.setText("${0}")
            }
        }

        vm.addCommentData.observe(this){
            if(it>0){
                ToastUtils.showLong("评论成功"+it)
//                LiveDataBus.sendComment(count+1)
                LiveDataBus.sendEvent(LiveDataBus.MyEvent("comment",count+1))
            }
        }

        vm.commentsData.observe(this){
            count=it.size
            etCount?.setText("评论数量：${it.size}")
            tv_comment?.setText("${it.size}")
            videoAdapter.data.get(position).commentnum=it.size
            videoAdapter.notifyItemChanged(position)
            it.forEach {
                val bean = Comment(
                    it.agreenum,
                    it.content,
                    it.createtime,
                    it.datatype,
                    it.id?.toLong(),
                    it.itemid,
                    it.nickname,
                    it.replytotal,
                    it.userid,
                    it.userlogo,
                    false,
                    0
                )
                vm.addCommentRoom(bean)
            }
            vm.getCommentsRoom(videoid)
        }

        vm.commentsRoomData.observe(this){
            commentAdapter.addData(it)
            commentAdapter.notifyDataSetChanged()
        }
        vm.commentsZanRoomData.observe(this){
            if(it>0){
                ToastUtils.showLong("赞成功")
            }else{
                ToastUtils.showLong("点赞失败")
            }
        }

        vm.getVideoRoomData.observe(this){
            videoAdapter.data.clear()
            videoAdapter.addData(0,
                VideoBeanItem(it.avatar_url,"",0,
                    vm.getDateTime(System.currentTimeMillis())
                    ,it.title,"",null,"","","","lr",
                    0,"","",it.title,"5319","","",it.videopath))
            videoAdapter.notifyDataSetChanged()
            vm.getVideos(1,10)
        }

    }

    override fun initView() {



//        LiveDataBus.getComment().observe(this){
//            etCount.setText("评论数量：${it}")
//        }
        LiveDataBus.getEnevt().observe(this){
            if(it.type=="comment"){
                etCount?.setText("评论数量：${it.content}")
            }
        }


        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.rvVideo.apply {
            adapter=videoAdapter
            layoutManager=linearLayoutManager
        }
        vm.getVideos(1,10)
        //仿抖音上下滑动分页效果
        val pagerSnapHelper= PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.rvVideo)


//        自动播放
        binding.rvVideo.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            val position = linearLayoutManager.findFirstVisibleItemPosition()//获取当前item的下标
//            index=position//保存下标 目的 为了后续关注、取消关注、点赞、评论等业务的处理
            val gsy: StandardGSYVideoPlayer =videoAdapter.getViewByPosition(position,R.id.gsy) as StandardGSYVideoPlayer  //播放控件
            gsy.startPlayLogic()
            iv_zan=videoAdapter.getViewByPosition(position, R.id.iv_love) as? ImageView
            tv_zan=videoAdapter.getViewByPosition(position, R.id.tv_love) as? TextView
            etCount=videoAdapter.getViewByPosition(position, R.id.etcount) as? TextView
            tv_comment=videoAdapter.getViewByPosition(position, R.id.tv_comment) as? TextView
            vm.getZan(videoAdapter.data.get(position).id)
            vm.getComments(videoAdapter.data.get(position).id)

        }

        videoAdapter.addChildClickViewIds(R.id.iv_comment,R.id.colose,R.id.iv_love,R.id.iv_share)
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            this.position=position
            val bean = videoAdapter.data.get(position)
            val commentLayout = adapter.getViewByPosition(position, R.id.llcomment)
            videoid=bean.id!!
            when(view.id){
                R.id.iv_comment->{
                    commentLayout?.visibility=View.VISIBLE

                    adapter.getViewByPosition(position, R.id.fasong)?.setOnClickListener {
                        val comment = adapter.getViewByPosition(position, R.id.et) as EditText
                        val item = CommentBeanItem(
                            0,
                            comment.text.toString(),
                            vm.getDateTime(System.currentTimeMillis()),
                            0,
                            null,
                            bean.id.toString(),
                            "lr",
                            emptyList(),
                            0,
                            5319,
                            bean.avatar_url
                        )

                        vm.addComment(item)
                        binding.rvVideo.setIntercept(false)
                    }

                    val rv = adapter.getViewByPosition(position, R.id.rv1) as RecyclerView
                    rv.apply {
                        this.adapter=commentAdapter
                        layoutManager=LinearLayoutManager(requireContext())
                    }
                }
                R.id.colose->{
                    commentLayout?.visibility=View.GONE
                    binding.rvVideo.setIntercept(true)
                }
                R.id.iv_love->{
                    if(tv_zan?.text.toString().toInt()==1){
                        tv_zan?.text="0"
                        iv_zan?.setImageResource(R.drawable.ic_action_nolove)
                        vm.deleteZan(VideoZanBean(videoid.toLong()))
                    }else{
                        tv_zan?.text="1"
                        iv_zan?.setImageResource(R.drawable.ic_xihuanred)
                        vm.addZan(VideoZanBean(videoid.toLong()))
                    }
                }
                R.id.iv_share->{
                    ARouter.getInstance().build("/video/VideoAddActivity").navigation()
                }
            }
        }

        commentAdapter.addChildClickViewIds(R.id.comm_zan)
        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            val comment = commentAdapter.data.get(position)
            if(comment.isZan){
                comment.isZan=false
                comment.zanNum=comment.zanNum-1
            }else{
                comment.isZan=true
                comment.zanNum=comment.zanNum+1
            }
            commentAdapter.notifyItemChanged(position)
            vm.commentsZanRoom(comment)

        }
    }

    override fun onResume() {
        super.onResume()
        vm.getVideoRoom()
    }

}